/**
 * Project: core.common
 * 
 * File Created at 2016年3月31日
 * 
 * Copyright 2015-2015 dx.com Croporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * DongXue software Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with dx.com.
 */
package com.dx.pf.commons.mail;

import java.security.Security;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

/**
 * @ClassName: MailSender
 * @Description: 邮件发送
 * @author wuzhenfang(wzfbj2008@163.com)
 * @date 2016年3月31日 上午11:00:52
 * @version V1.0
 */
@SuppressWarnings("restriction")
public class MailSender {
	
	static {
		Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
	}

	private String host;
	private String port;
	private String username;
	private String password;
	private Authenticator loginAuth;
	private Properties props;
	private String from;

	public void init() {
		props = new Properties();
		props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		props.setProperty("mail.smtp.socketFactory.fallback", "false");
		props.setProperty("mail.store.protocol", "smtp");
		props.setProperty("mail.smtp.host", host);
		props.setProperty("mail.smtp.port", port);
		props.setProperty("mail.smtp.socketFactory.port", port);
		props.put("mail.smtp.auth", "true");
		loginAuth = new Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(username, password);
			}
		};
	}

	/**
	 * 发送邮件给单收件人
	 * @param to 收件人
	 * @param subject 标题
	 * @param content 正文
	 * @param isHtml 是否为HTML
	 * @throws MessagingException 
	 */
	public void sendToSingle(String to, String subject, String content, boolean isHtml) throws MessagingException {
		List<String> list = new ArrayList<String>();
		list.add(to);
		send(list, subject, content, isHtml);
	}

	/**
	 * 发送邮件给多人
	 * @param mailAccount 邮件认证对象
	 * @param tos 收件人列表
	 * @param subject 标题
	 * @param content 正文
	 * @param isHtml 是否为HTML格式
	 * @throws MessagingException
	 */
	public void send(Collection<String> tos, String subject, String content, boolean isHtml) throws MessagingException {
		// 认证登录
		Session session = Session.getDefaultInstance(props, loginAuth != null ? new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(username, password);
			}
		} : null);

		Message mailMessage = new MimeMessage(session);
		mailMessage.setFrom(new InternetAddress(from));
		mailMessage.setSubject(subject);
		mailMessage.setSentDate(new Date());

		if (isHtml) {
			Multipart mainPart = new MimeMultipart();
			BodyPart html = new MimeBodyPart();
			html.setContent(content, "text/html; charset=utf-8");
			mainPart.addBodyPart(html);
		} else {
			mailMessage.setText(content);
		}

		for (String to : tos) {
			mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
			Transport.send(mailMessage);
		}
	}

	/**
	 * 发送邮件进行处理，根据处理结果返回数字 0是成功，1是地址错误，2是发送失败
	 * @param to
	 * @param subject
	 * @param content
	 * @return
	 * @throws AddressException
	 * @throws MessagingException
	 */
	public void sendSimpleText(String to, String subject, String content) throws AddressException, MessagingException {
		Session session = Session.getInstance(props, loginAuth);
		Message msg = new MimeMessage(session);
		msg.setFrom(new InternetAddress(username));
		msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
		msg.setSubject(subject);
		msg.setText(content);
		Transport.send(msg);
	}

	/**
	 * 以文本格式发送邮件
	 * @param mailInfo 待发送的邮件的信息
	 * @throws MessagingException 
	 */
	public boolean sendTextMail(MailEntity mailInfo) throws MessagingException {
		// 判断是否需要身份认证
		MyAuthenticator authenticator = null;
		Properties pro = mailInfo.getProperties();
		if (mailInfo.isValidate()) {
			// 如果需要身份认证，则创建一个密码验证器
			authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
		}
		// 根据邮件会话属性和密码验证器构造一个发送邮件的session
		Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
		try {
			// 根据session创建一个邮件消息
			Message mailMessage = new MimeMessage(sendMailSession);
			// 创建邮件发送者地址
			Address from = new InternetAddress(mailInfo.getFromAddress());
			// 设置邮件消息的发送者
			mailMessage.setFrom(from);
			// 创建邮件的接收者地址，并设置到邮件消息中
			Address to = new InternetAddress(mailInfo.getToAddress());
			mailMessage.setRecipient(Message.RecipientType.TO, to);
			// 设置邮件消息的主题
			mailMessage.setSubject(mailInfo.getSubject());
			// 设置邮件消息发送的时间
			mailMessage.setSentDate(new Date());
			// 设置邮件消息的主要内容
			String mailContent = mailInfo.getContent();
			mailMessage.setText(mailContent);
			// 发送邮件
			Transport.send(mailMessage);
			return true;
		} catch (MessagingException ex) {
			throw new MessagingException("发送邮件失败:" + ex.getMessage());
		}
	}
	
	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public String getPort() {
		return port;
	}

	public void setPort(String port) {
		this.port = port;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	/**
	 * @return the from
	 */
	public String getFrom() {
		return from;
	}

	/**
	 * @param from the from to set
	 */
	public void setFrom(String from) {
		this.from = from;
	}

}
